package cn.mesmile.admin.common.filter.xss;

import cn.hutool.core.util.StrUtil;
import cn.mesmile.admin.common.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;

/**
 * @author zb
 * @Description
 */
@Slf4j
public class XssRequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拦截文件上传 xss
        if (request instanceof StandardMultipartHttpServletRequest){
            StandardMultipartHttpServletRequest multipart = (StandardMultipartHttpServletRequest)request;
            Map<String, MultipartFile> fileMap = multipart.getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> iterator = fileMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, MultipartFile> next = iterator.next();
                MultipartFile value = next.getValue();
                String contentType = value.getContentType();
                String originalFilename = value.getOriginalFilename();
                if (StrUtil.containsAnyIgnoreCase(contentType+originalFilename, "<",">")){
                    throw new BusinessException("xss检查异常，文件名请勿包含'<'和'>'符号");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
